package com.cqwshzj.util;/**
 * @Description:
 * @Auther: Huang Zhijin
 * @Version: 1.0.0
 * @Date: 2021/4/7 10:53
 */

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.beans.BeanUtils.getPropertyDescriptor;
import static org.springframework.beans.BeanUtils.getPropertyDescriptors;

/**
 * 〈〉
 * @author Huang Zhijin
 * @create 2021/4/7
 * @since 1.0.0
 */
public class HzjBeanUtil {

	public static final List<String> DEFAULT_EXCLUSIVE_FIELDS = Arrays.asList("class","LOG","log","logger","LOGGER");



	public static void copyPropertiesIfNotNull(Object source, Object target) throws BeansException{
		copyPropertiesIfNotNull(source,target,null, (String[])null );
	}

	public static void copyPropertiesIfNotNull(Object source, Object target,  Class<?> editable,
							    String... ignoreProperties) throws BeansException {

		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		Class<?> actualEditable = target.getClass();
		if (editable != null) {
			if (!editable.isInstance(target)) {
				throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
						"] not assignable to Editable class [" + editable.getName() + "]");
			}
			actualEditable = editable;
		}
		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

		for (PropertyDescriptor targetPd : targetPds) {
			Method writeMethod = targetPd.getWriteMethod();
			if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null) {
					Method readMethod = sourcePd.getReadMethod();
					if (readMethod != null &&
							ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
						try {
							if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
								readMethod.setAccessible(true);
							}
							Object value = readMethod.invoke(source);
							//value为空则继续循环
							if (value == null) {
								continue;
							}
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						}
						catch (Throwable ex) {
							throw new FatalBeanException(
									"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
						}
					}
				}
			}
		}
	}

	/**
	 * map 转为 对象
	 * @param source
	 * @param targetClass
	 * @param <T>
	 * @return
	 */
	public static <T> T map2Obj(Map<String,Object> source , Class<T> targetClass){
		try {
			final T instance = targetClass.newInstance();
			BeanUtils.populate(instance,source);
			return instance;
		}catch (Exception e){
			throw new RuntimeException(" map2Obj transfer failed . source:<"+source+"> , targetClass:<"+targetClass+"> . ",e);
		}
	}

	/**
	 * obj 转为 Map
	 * @param obj
	 * @return
	 */
	public static Map<String,Object> obj2Map(Object obj){
		Map<String,Object> map = new HashMap<>();
		try {
			final BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
				String name = propertyDescriptor.getName();
				if ( DEFAULT_EXCLUSIVE_FIELDS.contains(name)) {
					continue;
				}
				final Method readMethod = propertyDescriptor.getReadMethod();
				Object value = readMethod != null ? readMethod.invoke(obj) : null;
				map.put( name, value );
			}
			return map;
		}catch (Exception e){
			throw new RuntimeException(" obj2Map transfer failed. obj: "+obj , e);
		}
	}


	/**
	 * 对象转map ，带有排除的字段
	 * @param obj
	 * @param exclusiveFields
	 * @return
	 */
	public static Map<String,Object> obj2Map(Object obj, String... exclusiveFields ){
		final Map<String, Object> map = obj2Map(obj);
		if (exclusiveFields != null && exclusiveFields.length > 0 ) {
			for (String field : exclusiveFields) {
				if ( StringUtils.isNotEmpty( field ) && map.containsKey(field) ) {
					map.remove( field );
				}
			}
		}
		return map;
	}
}
